package com.gepengjun.springboot.jwt.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource
    private StringRedisTemplate template;

    public void set(String key, String value, Long expire, TimeUnit timeUnit){
        template.opsForValue().set(key,value,expire,timeUnit);
    }

    public void set(String key, String value, Long expire){
        template.opsForValue().set(key,value,expire,TimeUnit.SECONDS);
    }

    public void set(String key, String value){
        template.opsForValue().set(key,value,600,TimeUnit.SECONDS);
    }

    public String get(String key){
        return template.opsForValue().get(key);
    }

    public boolean hasKey(String key){
        if (StringUtils.isEmpty(key)){
            return false;
        }
        return template.hasKey(key);
    }

    public Long getExpireTime(String key){
        return template.getExpire(key);
    }

    public boolean delete(String s) {
        return template.delete(s);
    }

    public void deleteByPattenn(String s) {
        Set<String> keys = template.keys(s);
        if (keys != null && keys.size() > 0){
            template.delete(keys);
        }
    }
}
